from ctypes import *
import ctypes

def pchangepoints(t, d1, d2, lamda, niter, all=True):
    lib = cdll.LoadLibrary("./rjmcmc/rjmcmc.so")
    class Data(ctypes.Structure):
        _fields_ = [("d1",POINTER(ctypes.c_double)), ("d2", POINTER(ctypes.c_double))]
    data = Data()
    cd1 = (ctypes.c_double*len(t))()
    cd2 = (ctypes.c_double*len(t))()  
    for i in range(len(t)):
        cd1[i] = c_double(d1[i])
        cd2[i] = c_double(d2[i])
    data.d1 = cd1
    data.d2 = cd2
    lib.getsample.argtypes = [POINTER(ctypes.c_double*len(t)), ctypes.c_int, POINTER(Data), ctypes.c_double, ctypes.c_int]

    class Particles(ctypes.Structure):
        _fields_ = [("cps", ctypes.POINTER(POINTER(ctypes.c_double))), ("its", ctypes.POINTER(POINTER(ctypes.c_double))), ("ncp", ctypes.POINTER(ctypes.c_int))]    
    lib.getsample.restype = Particles
    cT = ctypes.c_double*len(t)
    ct = cT()
    for i in range(len(t)):
        ct[i] = t[i]

    r =lib.getsample(byref(ct), ctypes.c_int(len(t)), byref(data), ctypes.c_double(lamda), ctypes.c_int(niter))
    rlist = []
    if all:
        cps = [0]*niter
        for i in range(niter):
            if r.ncp[i] > 0:
                thesecps = []
                for j in range(r.ncp[i]):
                    thesecps.append(r.cps[i][j])
                cps[i] = thesecps                
            else:
                cps[i]=[]
        return cps
    else:
        if r.ncp[niter-1] >= 0:
            cps = []
            for j in range(r.ncp[niter-1]):
                cps.append(r.cps[niter-1][j])
            return cps
        else:
            return []
